package com.cloud.school.app.service.impl;

import com.cloud.school.app.config.security.SecurityUserDetails;
import com.cloud.school.app.config.security.ValidateCode;
import com.cloud.school.app.model.UserModel;
import com.cloud.school.app.service.UserService;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static com.cloud.school.app.config.SecurityConfiguration.ROLE_ADMIN;
import static com.cloud.school.app.config.SecurityConfiguration.ROLE_USER;

/**
 * @ClassName SevurityUserDetailsService
 * @Description 登录验证服务类
 * @Author 36297
 * @Date 2018/12/2 23:49
 * @Version 1.0
 */
@Slf4j
@Service("userDetailsService")
public class SevurityUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private CacheService cacheService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if("18392686895".equals(username)){
            return new SecurityUserDetails(1544718896964l, username, "278695944@zhANG", Sets.newHashSet(ROLE_ADMIN));
        }
        UserModel userModel = userService.queryByPhoneNum(username);
        if (userModel == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        return new SecurityUserDetails(userModel.getId(), username, ValidateCode.getTeleValidateCode(cacheService, username), Sets.newHashSet(ROLE_USER));
    }
}
